/***** BEGIN LICENSE BLOCK *****
 * Version: CPL 1.0/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Common Public
 * License Version 1.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.eclipse.org/legal/cpl-v10.html
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * Copyright (C) 2007 Charles O Nutter <headius@headius.com>
 * 
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the CPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the CPL, the GPL or the LGPL.
 ***** END LICENSE BLOCK *****/
package asruby.runtime {

import asruby.exceptions.JumpException;
import asruby.lang.RubyArray;
import asruby.lang.RubyModule;
import asruby.lang.RubyObject;
import asruby.lang.RubyWarnings;
import asruby.parser.StaticScope;
import asruby.util.ArgsUtil;
/**
 * A Block implemented using a Java-based BlockCallback implementation
 * rather than with an ICallable. For lightweight block logic within
 * Java code.
 */
public class CompiledBlock extends BlockBody {
    protected  var callback:CompiledBlockCallback;
    protected  var hasMultipleArgsHead:Boolean;
    protected  var _arity:Arity;
    protected  var scope:StaticScope;
    
    public static function newCompiledClosure( self:IRubyObject,  frame:Frame,  visibility:Visibility,  klass:RubyModule,
         dynamicScope:DynamicScope,  arity:Arity,  scope:StaticScope,  
         callback:CompiledBlockCallback,  hasMultipleArgsHead:Boolean,  argumentType:int):Block {
        var binding: Binding =  new Binding(self, frame, visibility, klass, dynamicScope);
        var body: BlockBody =  new CompiledBlock(arity, scope, callback, hasMultipleArgsHead, argumentType);
        
        return new Block(body, binding);
    }
    
    public static function newCompiledClosure2( context:ThreadContext,  self:IRubyObject,  arity:Arity,
             scope:StaticScope,  callback:CompiledBlockCallback,  hasMultipleArgsHead:Boolean,  argumentType:int):Block {
        return newCompiledClosure(
                self,
                context.getCurrentFrame(),
                Visibility.PUBLIC,
                context.getRubyClass(),
                context.getCurrentScope(),
                arity,
                scope,
                callback,
                hasMultipleArgsHead,
                argumentType);
    }

    function CompiledBlock(arity:Arity, scope:StaticScope, callback:CompiledBlockCallback, hasMultipleArgsHead:Boolean, argumentType:int){
        super(argumentType);
        this._arity = arity;
        this.scope = scope;
        this.callback = callback;
        this.hasMultipleArgsHead = hasMultipleArgsHead;
    }
    
    public override function call(context:ThreadContext, args:Array, binding:Binding, type:int):IRubyObject{
        args = prepareArgumentsForCall(context, args, type);

        return yield2(context, context.getRuntime().newArrayNoCopy(args), null, null, true, binding, type);
    }

    public override function yield(context:ThreadContext, value:IRubyObject, binding:Binding, type:int):IRubyObject{
        return yield2(context, value, null, null, false, binding, type);
    }
    
    public  function yield2(context:ThreadContext, args:IRubyObject, self:IRubyObject, klass:RubyModule, aValue:Boolean, binding:Binding, type:int):IRubyObject{
        if (klass == null) {
            self = binding.getSelf();
            binding.getFrame().setSelf(self);
        }

        // handle as though it's just an array coming in...i.e. it should be multiassigned or just 
        // assigned as is to var 0.
        // FIXME for now, since masgn isn't supported, this just wraps args in an IRubyObject[], 
        // since single vars will want that anyway
        var oldVis: Visibility =  binding.getFrame().getVisibility();
        var realArgs: Array =  aValue ? 
                setupBlockArgs(context, args, self) : setupBlockArg(context, args, self); 
        pre(context, klass, binding);
        
        try {
            return callback.call(context, self, realArgs);
        } catch (bj:JumpException) {
        	
        }
        binding.getFrame().setVisibility(oldVis);
        post(context, binding);
        return null;
/*             if (bj.getTarget() == null) {
                bj.setTarget(this);
            } 
            throw bj;
        } catch (nj:JumpException.NextJump) {
            // A 'next' is like a local return from the block, ending this call or yield.
            return type == Block.Type.LAMBDA ? context.getRuntime().getNil() : IRubyObject(nj.getValue());
        } finally {
            binding.getFrame().setVisibility(oldVis);
            post(context, binding);
        }*/
    }
    
    protected  function pre(context:ThreadContext, klass:RubyModule, binding:Binding):void{
        context.preYieldSpecificBlock(binding, scope, klass);
    }
    
    protected  function post(context:ThreadContext, binding:Binding):void{
        context.postYield(binding);
    }

    private  function setupBlockArgs(context:ThreadContext, value:IRubyObject, self:IRubyObject):Array{
        switch (argumentType) {
        case ZERO_ARGS:
            return RubyObject.NULL_ARRAY;
        case MULTIPLE_ASSIGNMENT:
        case SINGLE_RESTARG:
            return [value];
        default:
            var length: int =  arrayLength(value);
            switch (length) {
            case 0:
                value = context.getRuntime().getNil();
                break;
            case 1:
                value = RubyArray(value).eltInternal(0);
                break;
            default:
                context.getRuntime().getWarnings().warn(RubyWarnings.MULTIPLE_VALUES_FOR_BLOCK, "multiple values for a block parameter (" +
                        length + " for 1)");
            }
            return [value];
        }
    }

    private  function setupBlockArg(context:ThreadContext, value:IRubyObject, self:IRubyObject):Array{
        switch (argumentType) {
        case ZERO_ARGS:
            return RubyObject.NULL_ARRAY;
        case MULTIPLE_ASSIGNMENT:
        case SINGLE_RESTARG:
            return null; //[ArgsUtil.convertToRubyArray(context.getRuntime(), value, hasMultipleArgsHead)];
        default:
            if (value == null) {
                context.getRuntime().getWarnings().warn(RubyWarnings.MULTIPLE_VALUES_FOR_BLOCK, "multiple values for a block parameter (0 for 1)");
                return [context.getRuntime().getNil()];
            }
            return [value];
        }
    }
    
    public override function getStaticScope():StaticScope{
        return scope;
    }

    public override function cloneBlock(binding:Binding):Block{
        binding = new Binding(binding.getSelf(),
                binding.getFrame().duplicate(),
                binding.getVisibility(),
                binding.getKlass(),
                binding.getDynamicScope());
        
        return new Block(this, binding);
    }

    public override function arity():Arity{
        return _arity;
    }
}
}